﻿using System;
using System.Net.Mail;
using System.IO;

using SsrsRenderStudio.Configuration;

namespace SsrsRenderStudio.Renderer.Output.Version2013
{
    public sealed class EmailOutput : Output
    {
        protected new EmailOutputParameters Parameters;

        public EmailOutput(EmailOutputParameters parameters) : base(parameters)
        {
            Parameters = parameters;
        }

        public override void Process()
        {
            sendMail();  
        }

        private void sendMail()
        {
            SmtpInfo info = ConfigurationManager.SmtpSettings();

            if (info == null)
            {
                //TODO: throw exception
            }

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient(info.SmtpHost);

            mail.From = new MailAddress(info.FromAddress, info.FromDisplayName);

            foreach (var rcpt in Parameters.Recipients)
            {
                mail.To.Add(rcpt);
            }

            mail.Subject = Parameters.MessageSubject;
            mail.Body = Parameters.MessageBody;
            mail.IsBodyHtml = Parameters.IsBodyHtml;

            //TODO: multiple page support
            MemoryStream ms = new MemoryStream(Parameters.RenderedReportBuffer[0]);
            Attachment att = new Attachment(ms, Parameters.FileName + "." + Parameters.FileExtension, Parameters.MimeContentType);
            mail.Attachments.Add(att);

            SmtpServer.Send(mail);
            
            
        }
       
    }
}
